import requests
from requests.auth import HTTPBasicAuth
from conf.sonar_config import *

class SonarQubeClient:
    def __init__(self, server_url, username, password):
        self.server_url = server_url
        self.auth = HTTPBasicAuth(username, password)

    def get_version(self):
        url = f'{self.server_url}/api/server/version'
        response = requests.get(url, auth=self.auth)
        if response.status_code == 200:
            return response.text
        else:
            print('Failed to get SonarQube version')
            print('Response:', response.text)
            return None

    def get_all_projects(self):
        url = f'{self.server_url}/api/projects/search'
        params = {'p': 1, 'ps': 100}  # Page number and page size
        all_projects = []

        while True:
            response = requests.get(url, params=params, auth=self.auth)
            if response.status_code == 200:
                data = response.json()
                all_projects.extend(data['components'])
                if data['paging']['total'] <= params['p'] * params['ps']:
                    break
                params['p'] += 1
            else:
                print('Failed to get projects')
                print('Response:', response.text)
                break

        return all_projects

# Example usage
if __name__ == '__main__':
    sonarqube_url = sonarqube_url
    username = sonarqube_username
    password = sonarqube_password

    client = SonarQubeClient(sonarqube_url, username, password)

    version = client.get_version()
    if version:
        print(f'SonarQube Version: {version}')

    projects = client.get_all_projects()
    if projects:
        print(f'Total Projects: {len(projects)}')
        for project in projects:
            print(f"Project Key: {project['key']}, Name: {project['name']}")
